﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZX.Web.UI.Controls;
using ZX.EHR.ResumeParseLib;
using System.Configuration;
using DevExpress.Web.ASPxUploadControl;
using System.IO;
using DevExpress.Web.ASPxClasses.Internal;
using System.Web.Caching;
using ZX.EHR.Library;
using System.Data;
using ZX.DAL.DBExtend;

namespace ZX.WebApp.EHR
{
    public partial class hrUpLoadHandwork : BasePage
    {
        static string resFileName = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                UploadControl.ShowProgressPanel = true;
            }
            string flag = this.GetStringFromQueryString("flag", "");
            if (flag.Trim() == "save")
            {
                this.SaveData();
            }
        }

        protected void UploadControl_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
        {
            try
            {
                e.CallbackData = SavePostedFiles(e.UploadedFile);
            }
            catch (Exception ex)
            {
                e.IsValid = false;
                e.ErrorText = ex.Message;
            }
        }

        string SavePostedFiles(UploadedFile uploadedFile)
        {
            if (!uploadedFile.IsValid)
                return string.Empty;

            FileInfo fileInfo = new FileInfo(uploadedFile.FileName);
            string path = Request.PhysicalApplicationPath + "upload/EHR/";
            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }
            resFileName = path + fileInfo.Name;
            uploadedFile.SaveAs(resFileName);

            ////读取EXCEL
            //DataTable dt = DbSql.ReadEcxel(resFileName, 1);
            //if (dt != null && dt.Rows.Count > 0)
            //{
            //    if (lstImportData == null)
            //    {
            //        lstImportData = new List<DataTable>();
            //    }
            //    lstImportData.Add(dt);
            //}
            RemoveFileWithDelay(uploadedFile.FileName, resFileName, 5);
            string fileLabel = fileInfo.Name;
            string fileLength = uploadedFile.ContentLength / 1024 + "K";
            return string.Format("{0} ({1})|{2}", fileLabel, fileLength, fileInfo.Name);
        }



        static void RemoveFileWithDelay(string key, string fullPath, int delay)
        {
            if (HttpUtils.GetCache()[key] == null)
            {
                DateTime absoluteExpiration = DateTime.Now.Add(new TimeSpan(0, delay, 0));
                HttpUtils.GetCache().Insert(key, fullPath, null, absoluteExpiration,
                    Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, new CacheItemRemovedCallback(RemovedCallback));
            }
        }
        static void RemovedCallback(string key, object value, CacheItemRemovedReason reason)
        {
            if (File.Exists(value.ToString()))
                File.Delete(value.ToString());
        }

        protected void SaveData()
        {
            /// <summary>
            /// 所有数据
            /// </summary>
            IList<DataTable> lstImportData = null;

            try
            {
                //读取EXCEL
                //string resFileName = Request.PhysicalApplicationPath + "upload/EHR/" + fileName;
                if (resFileName != "")
                {
                    lstImportData = new List<DataTable>();
                    DataTable dtExcel = DbSql.ReadEcxel(resFileName, 1);
                    if (dtExcel != null && dtExcel.Rows.Count > 0)
                    {
                        lstImportData.Add(dtExcel);
                    }
                    wkHandwork instance = null;
                    ZX.BLL.Extend.BaseBussnies wkCardDataBll = null;
                    foreach (DataTable dt in lstImportData)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            string empCode = dr["员工编号"].ToString().Trim();
                            Dictionary<string, string> dicEmpInfo = GetEmpInfos(empCode);
                            if (dicEmpInfo.Count > 0)
                            {
                                string employeeID = dicEmpInfo["EmployeeID"];
                                string employeeName = dicEmpInfo["EmployeeName"];
                                string employeeCode = dicEmpInfo["EmployeeCode"];
                                string id = "";
                                DateTime deadline = new DateTime();
                                DateTime.TryParse(dr["截止日期"].ToString(), out deadline);

                                decimal remTiaoxiuTime = 0, tiaoxiuTime = 0, workDayOverTime = 0, weekendOverTime = 0, holidayOverTime = 0, totalOverTime=0;
                                decimal.TryParse(dr["剩余调休"].ToString(), out remTiaoxiuTime);
                                decimal.TryParse(dr["已调休"].ToString(), out tiaoxiuTime);
                                decimal.TryParse(dr["加班合计"].ToString(), out totalOverTime);
                                decimal.TryParse(dr["工作加班"].ToString(), out workDayOverTime);
                                decimal.TryParse(dr["周末加班"].ToString(), out weekendOverTime);
                                decimal.TryParse(dr["节假日加班"].ToString(), out holidayOverTime);
                                instance = ZX.Common.Globals.getEntity("wkHandwork") as wkHandwork;
                                instance.EmployeeID = new Guid(employeeID);
                                instance.Deadline = deadline;
                                instance.RemTiaoxiuTime = remTiaoxiuTime;
                                instance.TiaoxiuTime = tiaoxiuTime;
                                instance.TotalOverTime = totalOverTime;
                                instance.WorkDayOverTime = workDayOverTime;
                                instance.WeekendOverTime = weekendOverTime;
                                instance.HolidayOverTime = holidayOverTime;

                                id = IsExistsData(employeeID, deadline);
                                if (id == "")
                                {
                                    wkCardDataBll = new ZX.BLL.Extend.BaseBussnies(instance);
                                    wkCardDataBll.Insert();
                                }
                                else
                                {
                                    instance.ID = new Guid(id);
                                    wkCardDataBll = new ZX.BLL.Extend.BaseBussnies(instance);
                                    wkCardDataBll.Update();
                                }
                            }
                        }
                    }
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("2");//文件未上传
                }
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write("0");
                throw ex;
            }
            finally
            {
                if (lstImportData != null)
                {
                    lstImportData.Clear();
                }
                resFileName = "";
            }
        }

        /// <summary>
        /// 根据导入的工号，匹配员工信息
        /// </summary>
        /// <param name="importEmpCode"></param>
        /// <returns></returns>
        protected Dictionary<string, string> GetEmpInfos(string importEmpCode)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            hrEmployee instance = ZX.Common.Globals.getEntity("hrEmployee") as hrEmployee;
            ZX.BLL.Extend.BaseBussnies hrBll = new ZX.BLL.Extend.BaseBussnies(instance);
            string condition = string.Format("EmployeeCode='{0}'", importEmpCode);
            ZX.EHR.Library.hrEmployee hrEmployee = hrBll.GetEntityByCondition(condition) as ZX.EHR.Library.hrEmployee;
            if (hrEmployee != null)
            {
                dic.Add("EmployeeID", hrEmployee.ID.ToString());
                dic.Add("EmployeeCode", hrEmployee.EmployeeCode);
                dic.Add("EmployeeName", hrEmployee.CName);
            }
            return dic;
        }

        /// <summary>
        /// 数据是否已经存在了
        /// </summary>
        /// <param name="employeeId"></param>
        /// <param name="deadline"></param>
        /// <returns></returns>
        protected string IsExistsData(string employeeId, DateTime deadline)
        {
            string id = "";
            wkHandwork instance = ZX.Common.Globals.getEntity("wkHandwork") as wkHandwork;
            ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies(instance);
            string condition = string.Format("EmployeeID='{0}' and Deadline='{1}'  ", employeeId, deadline);
            ZX.EHR.Library.wkHandwork wkHandwork = bll.GetEntityByCondition(condition) as ZX.EHR.Library.wkHandwork;
            if (wkHandwork != null)
            {
                id = wkHandwork.ID.ToString();
            }
            return id;
        }

    }
}